package com.db.patterns.bridge;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLUtils {

    public static Object getBean(String groupName, String name) throws DocumentException, InstantiationException, IllegalAccessException {
        InputStream inputStream = XMLUtils.class.getClassLoader().getResourceAsStream("config.xml");
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> parts = rootElement.elements();
        Element part = parts.stream().filter(item -> {
            return item.attributeValue("id").equals(groupName);
        }).findFirst().orElseThrow(() -> new RuntimeException("未找到指定id的元素"));
        List<Element> childrens = part.elements();
        Element element = childrens.stream().filter(item -> {
            return item.attributeValue("name").equals(name);
        }).findFirst().orElseThrow(() -> new RuntimeException("未找到指定name的元素"));
        String cName = element.getText();
        Class<?> aClass = null;
        try {
            aClass = Class.forName("com.db.patterns.bridge." + cName);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("配置内容错误，请检查com.db.patterns.bridge 是否存在类:" + cName);
        }
        return aClass.newInstance();
    }

    public static void main(String[] args) throws DocumentException, InstantiationException, IllegalAccessException {
        ImageImp os = (ImageImp) XMLUtils.getBean("linuxGroupPng", "os");
        Image image = (Image) XMLUtils.getBean("linuxGroupPng", "image");
        image.setImp(os);
        image.parseFile("迪迦奥特曼");
    }
}
